/**
 * @Author: langchenglai
 * @Date:   2018-04-23 19:01:21
 * @Email:  lclangcheng@gmail.com
 * @Filename: mysql.js
 * @Last modified by:   lclangcheng
 * @Last modified time: 2018-08-17 10:18:24
 * @License: jin10
 * @Copyright: jin10
 */
'use strict'

const log = require('../libs/logger')
const config = require('config')
const MySQL = require('mysql2')

const pool = MySQL.createPool({
  host: config.mysql['search'].host,
  port: config.mysql['search'].port,
  user: config.mysql['search'].user,
  password: config.mysql['search'].pass,
  database: config.mysql['search'].db,
  connectionLimit: 1
})

let query = (sql, values) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        log.error('MySQL:', err)
        log.error(sql, values)
        reject(err)
      } else {
        connection.query(sql, values, (err, rows) => {
          if (err) {
            log.error('MySQL:', err)
            log.error(sql, values)
            reject(err)
          } else {
            resolve(rows)
          }
          connection.release()
        })
      }
    })
  })
}

let heartbeat = async () => {
  try {
    await query('select 1')
  } catch (err) {
    log.error('heartbeat err', JSON.stringify(err))
  }
  setTimeout(heartbeat, 60 * 1000 * 10)
}
heartbeat()

module.exports = {
  query,
  pool
}
